<?php include 'header.php';?>

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

$con = mysqlConnect("awesome0");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if(!isset($_GET['month']))
{   
    $month =  date('m');
}
else
{
    $month = $_GET['month'];
}
    $year  =  date('y');

$purchasesFromThisMonth = mysqli_query($con,"SELECT *, sum(amount) as catSum FROM purchases WHERE date LIKE '".$month."%".$year."' GROUP BY type");

$categoryNames = mysqli_query($con,"SELECT categoryName FROM categories");

$catTotals = array();
$monthLimits = array();

while($row = mysqli_fetch_array($categoryNames))
{
    $catTotals[$row['categoryName']] =  [$row['categoryName'], 0];
    $monthlyLimits = mysqli_query($con,"SELECT limitamount FROM limits WHERE category = '".$row['categoryName']."' LIMIT 1");

    while($row2 = mysqli_fetch_array($monthlyLimits))
    {
        $monthLimits[$row['categoryName']] =  $row2['limitamount'] / 100;
    }
}

$total = 0;

while($row = mysqli_fetch_array($purchasesFromThisMonth))
{
    $total = $total + $row['catSum'];
    $catTotals[$row['type']][1] = $row['catSum'];   
}

   
     





$calendar = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
$calendarNames = ["Janurary", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
$currentMonth = $calendarNames[$month -1];

$lastDayInMonth = $calendar[$month - 1];


?>

<script type="text/javascript">
    
     function updateTimeline()
    {
        var date1 = document.getElementById('date1').value;
        var date2 = document.getElementById('date2').value;

         
                   var xmlhttp;
                    if (window.XMLHttpRequest)
                      {// code for IE7+, Firefox, Chrome, Opera, Safari
                      xmlhttp=new XMLHttpRequest();
                      }
                    else
                      {// code for IE6, IE5
                      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                      }
                    xmlhttp.onreadystatechange=function()
                      {
                      if (xmlhttp.readyState==4 && xmlhttp.status==200)
                        {
                        //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                        //alert(xmlhttp.responseText);
                            if(xmlhttp.responseText !== "ERROR")
                            {
                                
                            }
                           // alert(xmlhttp.responseText);
                            var obj = eval( '(' + xmlhttp.responseText +')');
                            
                            var totals = {'Miscellaneous': 0,'Phone Bill':0, 'Gas': 0, 'Dining': 0, 'Groceries': 0};
                            
                            var newHTML = "";
                            for(var i = 0; i < obj.length; i++)
                            {
                                newHTML = newHTML 
                                            + "<tr class='editTable' id='"+obj[i].id+"'>"
                                            + "<td>" + obj[i].date + "</td>"
                                            + "<td>" + obj[i].type + "</td>"
                                            + "<td>$" + parseInt(obj[i].amount / 100).toMoney() + "</td>"
                                            + "<td>" + obj[i].description + "</td>"
                                            +"<td style='text-align: right;'></td>"
                                            +"</tr>";
                                    
                                    totals[obj[i].type] = parseInt(totals[obj[i].type]) + parseInt(obj[i].amount);
                                        
                            }
                            
                            document.getElementById("tableTitle").innerHTML = "Purchases from " + date1 + " to " + date2;
                            document.getElementById("purchaseItems").innerHTML = newHTML;
                             document.getElementById("updatedTimelineTable").style.display = "block";
                             
                             document.getElementById("gasTotal").innerHTML =  "$" + (totals['Gas'] / 100).toMoney();          
                             document.getElementById("groceriesTotal").innerHTML = "$" + ( totals['Groceries']/ 100).toMoney();
                             document.getElementById("diningTotal").innerHTML =  "$" + (totals['Dining']/ 100).toMoney();
                             document.getElementById("miscTotal").innerHTML =  "$" + (totals['Miscellaneous']/ 100).toMoney();
                             document.getElementById("phoneTotal").innerHTML = "$" + ( totals['Phone Bill']/ 100).toMoney();
                             
                             document.getElementById("overallTotal").innerHTML = "$" + ( (totals['Gas'] + totals['Groceries'] + totals['Miscellaneous'] + totals['Phone Bill'] + totals['Dining']) / 100).toMoney();
                             
                             
                             
                             
                        }
                                                      
                      }
                    xmlhttp.open("GET","getData.php?date1="+date1+"&date2="+date2,true);
                    xmlhttp.send();
                    

    }
    $(function(){
        
        
    window.prettyPrint && prettyPrint();
    
    		$('#date1').datepicker({
				format: 'mm-dd-yyyy'
			});
                        $('#date2').datepicker({
				format: 'mm-dd-yyyy'
			});
			$('#dp2').datepicker();
			$('#dp3').datepicker();
			$('#dp3').datepicker();
			$('#dpYears').datepicker();
			$('#dpMonths').datepicker();
			
			
			var startDate = new Date(2012,1,20);
			var endDate = new Date(2012,1,25);
			$('#dp4').datepicker()
				.on('changeDate', function(ev){
					if (ev.date.valueOf() > endDate.valueOf()){
						$('#alert').show().find('strong').text('The start date can not be greater then the end date');
					} else {
						$('#alert').hide();
						startDate = new Date(ev.date);
						$('#startDate').text($('#dp4').data('date'));
					}
					$('#dp4').datepicker('hide');
				});
			$('#dp5').datepicker()
				.on('changeDate', function(ev){
					if (ev.date.valueOf() < startDate.valueOf()){
						$('#alert').show().find('strong').text('The end date can not be less then the start date');
					} else {
						$('#alert').hide();
						endDate = new Date(ev.date);
						$('#endDate').text($('#dp5').data('date'));
					}
					$('#dp5').datepicker('hide');
				});
                                
                                
                                
                    var button = document.createElement('button');
                        button.innerHTML = '<i class="icon-trash icon-white"></i>';
                        button.className = "btn btn-danger";
                        button.style.margin = "0px";
                        button.style.lineHeight = "10px";
                        button.style.padding= '4px';
                        button.onclick = function(){
                          var entryID = this.parentNode.parentNode.id;
                          
                          var cont = confirm("Are you sure you want to delete this?");
                         
                                   if(cont)
                          {
                              
                                    var currentIDs = "";
                                    $( "#newlyAddedPurchases tbody" ).children().each(function(){
                                       currentIDs = currentIDs + "-" + $(this).attr('id');
                                        
                                    });
                                    var xmlhttp;
                                     if (window.XMLHttpRequest)
                                       {// code for IE7+, Firefox, Chrome, Opera, Safari
                                       xmlhttp=new XMLHttpRequest();
                                       }
                                     else
                                       {// code for IE6, IE5
                                       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                       }
                                     xmlhttp.onreadystatechange=function()
                                       {
                                       if (xmlhttp.readyState==4 && xmlhttp.status==200)
                                         {
                                         //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                                         //alert(xmlhttp.responseText);
                                             if(xmlhttp.responseText !== "ERROR")
                                             {
                                                 
                                                 $("#"+entryID).remove();
                                             }
                                             
                                            // var replacementEntry = JSON.parse(xmlhttp.responseText);
                                             //alert(xmlhttp.responseText);
                                         }
                                       }
                                         xmlhttp.open("GET","deletePurchase.php?id="+entryID+"&currentIDs=" + currentIDs,true);
                                         xmlhttp.send();
                              
                            }// end if(cont)
                     };
                                
                                
                                        
                    $( "#newlyAddedPurchases" ).on('mouseover', 'tr', function() {
                      

                       
                       
                      // button.id = $(this).attr('id');
                       $(this).children('td:last-child').append(button);
                         //$(this).children('td:last-child').html('<a onclick="alert(); return false;" class="btn btn-danger" href="#" style="padding-top: 2px; padding-bottom: 2px; margin: 0px; font-size: 12px; line-height: 12px">X</a>');
                         
                        
                      }).on('mouseleave', 'tr', function() {
                       $(this).children('td:last-child').html("").empty();
                       

                      }).on('mousedown', 'tr', function() {
                          
                          
                         /* $(this).children().each(function() {    
                                var temp = $(this).html();
                                
                                if(temp.indexOf('button') < 0)
                                $(this).html('<input class="span2" type="text" value="'+temp+'"/>');
                                
                            });*/
                          
                      });

        // disabling dates
        var nowTemp = new Date();
        var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

        var checkin = $('#date1').datepicker({
          onRender: function(date) {
            return date.valueOf() < now.valueOf() ? 'disabled' : '';
          }
        }).on('changeDate', function(ev) {
          
        }).data('datepicker');
        
          var checkin = $('#date2').datepicker({
          onRender: function(date) {
            return date.valueOf() < now.valueOf() ? 'disabled' : '';
          }
        }).on('changeDate', function(ev) {
          if (ev.date.valueOf() > checkout.date.valueOf()) {
            var newDate = new Date(ev.date)
            newDate.setDate(newDate.getDate() + 1);
            checkout.setValue(newDate);
          }
          checkin.hide();
          $('#dpd2')[0].focus();
        }).data('datepicker');
        
        
        
        var checkout = $('#dpd2').datepicker({
          onRender: function(date) {
            return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
          }
        }).on('changeDate', function(ev) {
          checkout.hide();
        }).data('datepicker');
		});
                
             Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{ 
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
   d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)

   /*
   according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined' 
   rather than doing value === undefined.
   */   
   t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   //extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '', 

   j = ((j = i.length) > 3) ? j % 3 : 0; 
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); 
}
    
    </script>


        <h2><?php echo $currentMonth.', 20'.$year;?></h2>
<div class="span7" style="margin-top: 0px;">
<table class="table table-bordered">
    <thead>
        <tr>
            <th></th>
            <th>Total this month</th>
            <th>Monthly limit</th>
            <th>Available balance</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($catTotals as $currentCategory) 
        {
                
                $currentCategoryTotal = $currentCategory[1] / 100;
                $categoryName = $currentCategory[0];
                $currentLimit = $monthLimits[$categoryName];
        
        ?>
     
        
        <tr <?php if($currentLimit < $currentCategoryTotal) {echo 'class="error" style="color: red;"';};?>>
            <td style="font-weight: 900;"><?php echo $categoryName;?></td>
            <td ><?php echo '$' . number_format($currentCategoryTotal, 2);?></td>
            <td><?php echo '$' .number_format($currentLimit, 2);?></td>
            <td><?php echo '$' . number_format($currentLimit - ($currentCategoryTotal), 2); ?></td>
             
        </tr>
        <?php }?>
        
        
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
           <tr style="font-size: 14pt; font-weight: 900;">
               <td colspan="3" style="text-align: right;">TOTAL: </td>
            <td><?php echo '$'. number_format($total / 100, 2);?></td>
        </tr>
    </tbody>
</table>
</div>
    <div class="span4">
        <div class="well">
        Or choose a different month:
        
        <form action="index.php" method="get">
            <select name="month">
                <?php 
                $i = 1;
                foreach($calendarNames as $monthName)
                {
                  echo "<option value='".$i."'>".$monthName."</option>";  
                  $i++;
                }
                ?>
            </select>
            <button type="submit" class="btn btn-primary">Change month</button>
        </form>
        </div>
        <a href="settings.php">Change monthly limits</a>
    </div>
         
    <div class="span12" style="border-top: solid thin #eaeaea; padding-top: 25px; ">
        This is where you can calculate totals from other dates:
    </div>
    
    <div class="span9">
    <div class="well">
        <div class="form-inline">
            <input type="text" class="span2" value="<?php echo $month;?>-01-20<?php echo $year;?>" id="date1" placeholder="Date of purchase">
                through
                <input type="text" class="span2" value="<?php echo $month;?>-<?php echo $lastDayInMonth;?>-20<?php echo $year;?>" id="date2" placeholder="Date of purchase"/>
                <button class="btn btn-primary" onclick="updateTimeline();">Get new data</button>
            </div>
</div>
    
    <div class="bs-docs-example" id="updatedTimelineTable" style="display: none;">
<legend id="tableTitle"></legend>
<table class="table table-striped table-hover" style="font-size: 10pt;" id="newlyAddedPurchases">
    <thead>
        <tr>
            <th>Date</th>
            <th>Category</th>
            <th>Amount</th>
            <th>Description</th>
            <th style="visibility: hidden;"><a class="btn btn-danger" href="#"><i class="icon-trash icon-white"></i> Delete</a></th>
        </tr>    
    </thead>
    <tbody id="purchaseItems">
     
    </tbody>
</table>
</div>
    </div>
    <div class="span2">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Category</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody id="totalsTable">
                <tr>
                    <td>Gas</td>
                    <td id="gasTotal"></td>   
                </tr>
                <tr>
                    <td>Dining</td>
                    <td id="diningTotal"></td>   
                </tr>
                <tr>
                    <td>Groceries</td>
                    <td id="groceriesTotal"></td>   
                </tr>
                <tr>
                    <td>Misc.</td>
                    <td id="miscTotal"></td>   
                </tr>
                <tr>
                    <td>Phone</td>
                    <td id="phoneTotal"></td>   
                </tr>
                 <tr>
                    <td>TOTAL</td>
                    <td id="overallTotal"></td>   
                </tr>
            </tbody>
        </table>
        
    </div>
    
</span>
<?php include 'footer.php';?>